﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CharacterCreation.Data.Models {
    /// <summary>
    /// A generic character statistic class
    /// </summary>
    /// <typeparam name="T"></typeparam>
    [Serializable]
    public class CharacterStatistic<T> : CharacterXPCoupling where T : Statistic, new() {
        
        /// <summary>
        /// Gets or sets the Statistic
        /// </summary>
        public T Statistic {
            get { return _Statistic; }
            set {
                _Statistic = value;
                RaisePropertyChanged("Statistic");
            }
        }
        private T _Statistic;

        /// <summary>
        /// Gets or sets the StartingValue
        /// </summary>
        public int StartingValue {
            get { return _StartingValue; }
            set {
                _StartingValue = value;
                RaisePropertyChanged("StartingValue");
                RaisePropertyChanged("Score");
            }
        }
        private int _StartingValue;


        /// <summary>
        /// Gets or sets the RacialBonus
        /// </summary>
        public int RacialBonus {
            get { return _RacialBonus; }
            set {
                _RacialBonus = value;
                RaisePropertyChanged("RacialBonus");
                RaisePropertyChanged("Score");
            }
        }
        private int _RacialBonus;
        
        /// <summary>
        /// Gets or sets the Score
        /// </summary>
        public int Score {
            get { return CalculateStatistic(); }
        }

        /// <summary>
        /// Calculates the statistic
        /// </summary>
        /// <returns></returns>
        public virtual int CalculateStatistic() {
            createStatistic();
            int score =  Statistic.CalculateStatistic(this.StartingValue, this.RacialBonus, this.TotalXP);
            T stat = DataContext.GetAll<T>(s => s.Level == score).FirstOrDefault();
            
            this.Statistic = stat;
            return score;
        }

        private void createStatistic() {
            if (this.Statistic == null) {
                if (typeof(HitPoints).IsAssignableFrom(typeof(T)) || typeof(Essence).IsAssignableFrom(typeof(T))) this.Statistic = new T();
                else this.Statistic = DataContext.GetAll<T>().First();
            }
        }

        public CharacterStatistic() {
        }
    }
}
